//
//  YXStatuesViewModel.swift
//  SinaWeiBo
//
//  Created by Vergil on 2017/5/24.
//  Copyright © 2017年 Vergil. All rights reserved.
//

import Foundation
import YYModel

class YXStatuesViewModel {
    
    /// 上拉最大错误次数
    private let maxUpErroeCount = 1
    
    /// 数据列表
    lazy var statuesList = [YXStatuesModel]()
    
    /// 上拉错误次数
    lazy var upErrorCount = 0
    
    /// 上拉下拉加载数据
    ///
    /// - Parameters:
    ///   - isLoadMore: 是否正在上拉
    ///   - completion: 完成回调
    func loadStatuesList(isLoadMore: Bool, completion: @escaping (_ isSuccess: Bool)->()) {
        
        /// 如果上拉刷新错误次数大于最大次数,就不再请求数据了
        if isLoadMore && upErrorCount >= maxUpErroeCount {
            return
        }
        
        //取出第一个的id
        let firstId = isLoadMore ? 0 : (statuesList.first?.id ?? 0)
        //去除最后一个的id
        let lastId = isLoadMore ? (statuesList.last?.id ?? 0) : 0
        
        YXNetWork.Manager.getStatusList(since_id: firstId, max_id: lastId) { (list, isSuccess) in
            
            let array = NSArray.yy_modelArray(with: YXStatuesModel.self, json: list ?? []) as! [YXStatuesModel]
            
            print("加载了\(array.count)条数据")
            
            self.statuesList = isLoadMore ? (self.statuesList + array) : (array + self.statuesList)
            
            if isLoadMore && array.count == 0 {
                
                self.upErrorCount += 1
                completion(false)
                
            } else {
               
                completion(isSuccess)
                
            }
            
        }
        
    }
    
}
